package com.ahui.server.config.serurity;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * JWT登录授权过滤器
 * @author ahui on 2021/4/22
 */
public class JwtAuthencationTokenFilter extends OncePerRequestFilter {

    /**
     * 主配置文件中配置的tokenHeader： Authorization
     */
    @Value("${jwt.tokenHeader}")
    private String tokenHeader;

    /**
     * 主配置文件中配置的tokenHead： Bearer
     */
    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @Autowired
    private JwTokenUtil jwTokenUtil;
    @Autowired
    private UserDetailsService userDetailsService;

    /**
     * 前置拦截
     *
     * @param request
     * @param response
     * @param filterChain
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        // 1. 通过request获取header,header就是前端传给我们的一个Authorization
        String authHeader = request.getHeader(tokenHeader);
        // 存在token
        // 思路： 判断能不能根据Authorization 和 是不是Bearer开头的
        if (null != authHeader && authHeader.startsWith(tokenHead)){
            String authToken = authHeader.substring(tokenHead.length());
            String username = jwTokenUtil.getUserNameFromToken(authToken);
            //token存在，用户名但是未登录
            if(null != username && null == SecurityContextHolder.getContext().getAuthentication()){
                //给他登录
                UserDetails userDetails = userDetailsService.loadUserByUsername(username);
                //判断token是否有效，如果有效则放进用户对象
                if(jwTokenUtil.validateToken(authToken,userDetails)){
                    UsernamePasswordAuthenticationToken authenticationToken =
                            new UsernamePasswordAuthenticationToken(userDetails,null,userDetails.getAuthorities());
                    authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                }
            }
        }
        filterChain.doFilter(request,response);
    }
}
